import bencoder
from util.packagepretreat import bytes2str_dict
def krcp(data:bytes) -> dict:
    krcp = Krcp.decode(data)
    #print(krcp)
    if krcp:
        return krcp.krcp_dict
    else:
        return None

class Krcp():
    def __init__(self,krcp_dict:dict):
        self.krcp_dict = krcp_dict
        
    @classmethod
    def decode(cls,data:bytes):
        try:
            result = bencoder.bdecode(data)
            result = bytes2str_dict(result)
            # print(result)
            # result['a']['id'] = result['a']['id'].hex()
            # result['a']['info_hash'] = result['a']['info_hash'].hex()
            # result['t'] = result['t'].hex()
            # result['v'] = str.encode(result['v']).hex()
            # result['a']['want'] = ''.join(bytes.decode(i) for i in result['a']['want'])
            return cls(result)
        except Exception as e:
            #print(e)
            return None

